﻿using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;
using QUANLYSINHVIEN.Domain;

namespace QUANLYSINHVIEN.Sevice
{
    public class SinhVienService
    {
        //private ISession mySession;
        private static ISessionFactory _mySecsionFactory;

        private static ISession OpenSession()
        {
            if (_mySecsionFactory == null)
            {
                var configuration = new Configuration();
                configuration.AddAssembly(Assembly.GetCallingAssembly());

                _mySecsionFactory = configuration.BuildSessionFactory();
            }
            return _mySecsionFactory.OpenSession();
        }

        public static IList<SinhVien> LoadSinhVien()
        {
            using (var mySession = OpenSession())
            {
                var list = mySession.CreateQuery("FROM SinhVien as sv").List<SinhVien>();
                return list;
            }
        }

        public static void ThemSinhVien(String mssv, String tenSv, String lop, String diaChi)
        {
            using (var mySession = OpenSession())
            {
                var addSinhVien = new SinhVien {MSSV = mssv, TENSV = tenSv, LOP = lop, DIACHI = diaChi};
                mySession.Save(addSinhVien);
            }
        }

        public static void SuaSinhVien(int id, String mssv, String tenSv, String lop, String diaChi)
        {
            using (var mySession = OpenSession())
            {
                var a = mySession.CreateQuery(
                        "Update SinhVien set MSSV = :mssv, TENSV = :tensv, LOP = :lop, DIACHI = :diachi where ID = :id")
                        .SetParameter("mssv", mssv)
                        .SetParameter("tensv", tenSv)
                        .SetParameter("lop", lop)
                        .SetParameter("diachi", diaChi)
                        .SetParameter("id", id)
                        .ExecuteUpdate();
            }
        }

        public void XoaSinhVien(int id)
        {
            using (var mySession = OpenSession())
            {
                mySession.CreateQuery("DELETE FROM SinhVien o WHERE o.ID = :id")
                    .SetParameter("id", id)
                    .ExecuteUpdate();
            }
        }
    }
}
